import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../FandCar/DriverIntroduction.dart';
import '../FandCar/SelectSourceOfGoods.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../http/getapi.dart';
import '../l10n/messages.dart';
import 'AddGoodsFirst.dart';
import 'DesignatedDriver.dart';
import 'package:platform/platform.dart';

import 'SendGoodsMain.dart';

class SourceDetails extends StatefulWidget {
  const SourceDetails({super.key, required this.id, required this.shipperId, required this.checkPage});
  final String id;
  final  String shipperId;
  final int checkPage;
  @override
  State<SourceDetails> createState() => _SourceDetailsState();
}

class _SourceDetailsState extends State<SourceDetails> {
  bool isFirstSelected = true;
  Map dataMap = {};
  List driverList=[];
  //1发货历史 2常发货源
  int sourceType=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getDetailsAction(widget.id,widget.shipperId);

    if(widget.checkPage==2){
      isFirstSelected = false;

    }
  }

  void getDetailsAction(String id,String shipperId) async {

    getApiManager.getData(
      context,
      MyServiceUrl.goodsdetail,
      {
        "id":id,
        "shipperId":shipperId
      },
          (responseData) async {
          setState(() {
            if(responseData['data']==null){
              getApiManager.getData(
                context,
                "api/goods/goods/common/detail",
                {
                  "id":id,
                },
                    (responseData) async {
                  setState(() {
                    sourceType=2;
                    dataMap = responseData['data'];
                  });

                },
              );
            }else {
              dataMap = responseData['data'];

            }
          });

      },
    );


  }


//删除货源
  void deleteBillAction(String id,String shipperId)async{
    ApiManager.postData(
      context,
      'api/goods/goods/offline',
      {
        "id":id,
      },
          (responseData) async {
            BrnToast.show("删除成功", context,);
            Navigator.pop(context,"success");
      },
    );
  }
  //获取已联系司机列表
  void getDriverDataAction(String id,String shipperId) async {
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.DriverCantact,
      {"current":1,"size":20,"goodsId":dataMap['id']},
          (responseData) async {
        setState(() {
          driverList= responseData['data']['records'];
        });

      },
    );

  }
  // void addOftenAction()async{
  //   ApiManager.postData(
  //     context,
  //     'api/goods/goods/common/add',
  //     dataMap,
  //         (responseData) {
  //       setState(() {
  //         print(responseData);
  //         BrnToast.show("添加成功", context);
  //
  //
  //       });
  //     },
  //   );
  // }
  void deleteOftenBillAction(String id)async{
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(MyServiceUrl.header + 'api/goods/goods/common/delete',
      data:
      [
        {
          "id": id
        }
      ]
      ,
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("删除成功", context);
        Navigator.pop(context,"success");
        } else {

          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      BrnToast.show(error.toString(), context);
      ;
    });


  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("货源详情",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body: Column(
          children: [
      Expanded(
        child:ListView(
        children: [
          dataMap['status']==1?
          Container(
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),
            padding: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      child: Column(
                        children: [
                          Text("基本信息",style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight:isFirstSelected? FontWeight.w600:FontWeight.w100),),
                          SizedBox(height: 8.h,),
                          Container(
                            width: 20.w,
                            height: 2.h,
                            color: isFirstSelected?MyColors.themeColor:Colors.white,
                          ),
                        ],
                      ),
                      onTap: (){
                        setState(() {
                          isFirstSelected=true;
                        });
                      },
                    ),
                    SizedBox(width: screenSize.width/4,),
                    GestureDetector(
                      child: Column(
                        children: [
                          Text("已联系司机",style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight:isFirstSelected? FontWeight.w100:FontWeight.w600),),
                          SizedBox(height: 8.h,),
                          Container(
                            width: 20.w,
                            height: 2.h,
                            color:isFirstSelected?Colors.white: MyColors.themeColor,
                          ),
                        ],
                      ),
                      onTap: (){
                        setState(() {
                          getDriverDataAction(dataMap['id'], widget.shipperId);
                          isFirstSelected=false;
                        });
                      },
                    ),
                  ],

                ),

              ],
            ),
          ):SizedBox(height: 10,),
          SizedBox(height:1.h,),
          if(!dataMap.isEmpty)
             isFirstSelected ?
               GoodsBasicInformation(dataMap: dataMap,)
                  : getDriverList(dataList: driverList,
                id: dataMap['id'],
                shipperId: dataMap['shipperId'],),

        ],
      ),
      ),
      Container(
      padding: EdgeInsets.only(top: 15.h,left: 15.w,right: 15.w,bottom: 44.h),
       decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(10))),
        child:dataMap['status']==1? Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(),
            GestureDetector(
              child:  Container(
                  width: 80.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("指定司机",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: (){
                Navigator.push( context, FadeRoute(page:DesignatedDriver(
                  orderId:widget.id,
                  shipperId:widget.shipperId, type: 1,
                )));
              },
            ),
            GestureDetector(
              child:  Container(
                  width: 60.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("改价",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: ()async{
                List<String> typeList=["趟","吨","方"];
                if(dataMap['cargoInfo'][0]['cargoVolume']==0){
                  typeList.remove("方");
                }
                if(dataMap['cargoInfo'][0]['cargoWeight']==0){
                  typeList.remove("吨");
                }
                final result = await showModalBottomSheet(
                    context: context,
                    isScrollControlled: true,
                    isDismissible: false,
                    // 设置为 false，点击外部区域不关闭
                    enableDrag: false,
                    // 设置为 false，禁用上滑手势关闭
                    builder: (BuildContext context) {
                      return MyBidSheet(
                        id: widget.id, goodsWeight: dataMap['cargoInfo'][0]['cargoWeight'].toString(), goodsValume: dataMap['cargoInfo'][0]['cargoVolume'].toString(), shipperId: widget.shipperId,Price:dataMap['freight'], priceUnit: dataMap['priceUnit'],);
                    }
                );
                if (result != null) {
                  setState(() {

                  });
                }
              },
            ),

            GestureDetector(
              child:  Container(
                  width: 80.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("删除货源",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: (){
                showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return BrnDialog(
                      titleText: '提示',
                      messageText:'确定删除该货源？',
                      actionsWidget: [
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: Text("取消",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        ),
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                            deleteBillAction(dataMap["id"], dataMap['shipperId']);

                          },
                          child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                        ),
                      ],
                    );
                  },
                );

              },
            ),

            GestureDetector(
              child:  Container(
                  width: 60.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("编辑",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: ()async{
              final result=await  Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                  dataMap:dataMap, editType: 2,
                )));
                if(result!=null){
                  getDetailsAction(widget.id,widget.shipperId);
                }
              },
            ),
            SizedBox(),
          ],
        ):Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [

            GestureDetector(
              child:  Container(
                  width: 80.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("编辑",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: ()async{
                final result=await  Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                  dataMap:dataMap, editType:sourceType==1? 2:4,
                )));
                if(result!=null){
                  getDetailsAction(widget.id,widget.shipperId);
                }
              },
            ),
            SizedBox(width: 10.w,),
            GestureDetector(
              child:  Container(
                  width: sourceType==1?80.w:60.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text(sourceType==1?"存为常发":"删除",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: ()async{
                if(sourceType==1) {
                  ApiManager.postData(
                    context,
                    'api/goods/goods/common/add',
                    Map<String, dynamic>.from(dataMap),
                        (responseData) {
                      setState(() {
                        print(responseData);
                        BrnToast.show("添加成功", context);
                        // getGoodsHistory(1);

                      });
                    },
                  );
                }else{
                  deleteOftenBillAction(dataMap['id']);
                }
              },
            ),
            SizedBox(width: 10.w,),
            GestureDetector(
              child:  Container(
                  width: 80.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30.0),
                    border: Border.all(
                      color: MyColors.themeColor,
                      width: 1.0,
                    ),
                  ),
                  child: Center(child: Text("再发一单",style: TextStyle(fontSize: 14.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),)
              ),
              onTap: (){
                Navigator.push( context, FadeRoute(page:AddGoodsFirst(
                  dataMap: dataMap, editType: 3,
                )));
              },
            ),

            
          ],
        ),
      ),
        ],
      ),

    );
  }
}
class GoodsBasicInformation extends StatefulWidget {
  const GoodsBasicInformation({super.key, required this.dataMap});
    final Map dataMap;
  @override
  State<GoodsBasicInformation> createState() => _GoodsBasicInformationState();
}

class _GoodsBasicInformationState extends State<GoodsBasicInformation> {
  String dintanceStr="1000";
  //获取里程
  Future<void> getGotoDisAction() async {

    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.get<String>("https://api.map.baidu.com/directionlite/v1/driving?origin=${widget.dataMap['unloadPlaceInfo'][0]['latitude']},${widget.dataMap['unloadPlaceInfo'][0]['longitude']}&destination=${widget.dataMap['loadPlaceInfo'][0]['latitude']},${widget.dataMap['loadPlaceInfo'][0]['longitude']}&ak=Pb9qx5M4d02snVGSQaEqGVpqybA18AS8")
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(r.toString());
        // 获取code和data
        String code = jsonMap['status'].toString();
        if (code == "0") {
          setState(() {
            List list =jsonMap['result']['routes'];
            dintanceStr = list[0]['distance'].toString();
          });
        } else {
          // BrnToast.show(jsonMap['message'], context);
        }
        // 打印结果
        print('Code: $code');
      });
    }).catchError((error) {
      print(error);
    });

  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getGotoDisAction();
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          padding: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,bottom: 8.h),
          margin: EdgeInsets.only(left: 10.w,right: 10.w),
          child: Column(
            children: [
              Row(
                children: [
                  Text("装卸信息",style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w600),),
                  SizedBox(width: 8.w,),
                  if(widget.dataMap['invoiceType']==1)
                    Image.asset("lib/Images/OrderList/专票标签.png",width: 30.w,height: 18.h,),
                  SizedBox(width: 4.w,),
                  if(widget.dataMap['category']==1)
                    Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                ],
              ),
              SizedBox(height: 8.h,),
              Row(
                children: [
                  Icon(Icons.access_time,size: 20,color: MyColors.hintColor,),
                  Text(widget.dataMap['loadDay']+" "+widget.dataMap['loadTime']+"点装货",style: TextStyle(color: MyColors.textColor),),
                ],
              ),
              SizedBox(height: 8.h,),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [

                  Column(
                    children: [
                      Image.asset("lib/Images/OrderList/装货点icon.png",
                        width: 20.w, height: 20.h,),
                      Image.asset(
                        "lib/Images/OrderList/垂直虚线.png", width: 18.w,
                        height: 20.h,),
                      if(widget.dataMap["loadPlaceInfo"].length == 2&&widget.dataMap["loadPlaceInfo"][1]!=null)
                        Column(
                          children: [
                            Image.asset(
                              "lib/Images/OrderList/装货点icon.png",
                              width: 20.w, height: 20.h,),
                            Image.asset(
                              "lib/Images/OrderList/垂直虚线.png",
                              width: 18.w, height: 20.h,),
                          ],
                        ),
                      if( widget.dataMap["unloadPlaceInfo"].length == 2&&widget.dataMap["unloadPlaceInfo"][1]!=null)
                        Column(
                          children: [
                            Image.asset(
                              "lib/Images/OrderList/卸货点icon.png",
                              width: 20.w, height: 20.h,),
                            Image.asset(
                              "lib/Images/OrderList/垂直虚线.png",
                              width: 18.w, height: 20.h,),
                          ],
                        ),

                      Image.asset("lib/Images/OrderList/卸货点icon.png",
                        width: 20.w, height: 20.h,),
                    ],
                  ),
                  SizedBox(width: 8.w,),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // SizedBox(height: 8.h,),
                      Row(
                        children: [
                          Text(
                            widget.dataMap["loadPlaceInfo"][0]["city"] +
                                " " +
                                widget.dataMap["loadPlaceInfo"][0]["county"],
                            style: TextStyle(
                                color: Colors.black, fontSize: 14.sp,fontWeight: FontWeight.w600),),
                          SizedBox(width: 8.w,),


                        ],
                      ),
                      Container(
                        width: screenSize.width-100.w,
                        child: Text(
                          widget.dataMap["loadPlaceInfo"][0]["address"],
                          style: TextStyle(
                              color: MyColors.textColor,overflow: TextOverflow.ellipsis,
                              fontSize: 12.sp),),
                      ),

                      SizedBox(height: 8.h,),
                      if(widget.dataMap["loadPlaceInfo"].length == 2&&widget.dataMap["loadPlaceInfo"][1]!=null)
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text(
                                  widget.dataMap["loadPlaceInfo"][1]["city"] +
                                      " " +
                                      widget.dataMap["loadPlaceInfo"][1]["county"],
                                  style: TextStyle(color: Colors.black,
                                      fontSize: 14.sp,fontWeight: FontWeight.w600),),
                              ],
                            ),

                            Container(
                              width: screenSize.width-100.w,
                              child: Text(
                                widget.dataMap["loadPlaceInfo"][1]["address"],
                                style: TextStyle(
                                    color: MyColors.textColor,overflow: TextOverflow.ellipsis,
                                    fontSize: 12.sp),),
                            ),

                            SizedBox(height: 8.h,),
                          ],
                        ),

                      Row(
                        children: [
                          Text(
                            widget.dataMap["unloadPlaceInfo"][0]["city"] +
                                " " +
                                widget.dataMap["unloadPlaceInfo"][0]["county"],
                            style: TextStyle(
                                color: Colors.black, fontSize: 14.sp,fontWeight: FontWeight.w600),),
                          SizedBox(width: 8.w,),

                        ],
                      ),
                      Container(
                        width: screenSize.width-100.w,
                        child: Text(
                          widget.dataMap["unloadPlaceInfo"][0]["address"]!=null?widget.dataMap["unloadPlaceInfo"][0]["address"]:"--",
                          style: TextStyle(
                              color: MyColors.textColor,overflow: TextOverflow.ellipsis,
                              fontSize: 12.sp),),
                      ),


                      if(widget.dataMap["unloadPlaceInfo"].length == 2&&widget.dataMap["unloadPlaceInfo"][1]!=null)
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height: 8.h,),
                            Row(
                              children: [
                                Text(
                                  widget.dataMap["unloadPlaceInfo"][1]["city"] +
                                      " " +
                                      widget.dataMap["unloadPlaceInfo"][1]["county"],
                                  style: TextStyle(color: Colors.black,
                                      fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                // SizedBox(width: 8.w,),
                                // Text(
                                //   widget.dataMap['unloadDay']+" "+widget.dataMap['unloadTime']+"点装货",
                                //   style: TextStyle(color: MyColors.textColor,
                                //       fontSize: 12.sp),),
                              ],
                            ),

                            Container(
                              width: screenSize.width-100.w,
                              child: Text(
                                widget.dataMap["unloadPlaceInfo"][1]["address"],
                                style: TextStyle(
                                    color: MyColors.textColor,overflow: TextOverflow.ellipsis,
                                    fontSize: 12.sp),),
                            ),
                          ],
                        ),

                    ],

                  ),
              ],
              ),
              Divider(height: 16.h,color: MyColors.backgreyColor,),
              GestureDetector(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Row(

                      children: [
                        Text("预估运输里程",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        Text(convertMetersToKilometers(dintanceStr)+"公里",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        SizedBox(width: 8.w,),
                        // Text("全程",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        // Text(convertMetersToKilometers(dintanceStr),style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp),),
                        // Text("公里",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                      ],
                    ),
                    // Text("查看路线",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                  ],
                ) ,
              ),

            ], 
          ),
        ),
        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          padding: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,bottom: 8.h),
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("车货信息",style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w600),),
              Divider(height: 16.h,color: MyColors.backgreyColor,),
              Row(
                children: [
                  Text("车辆",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                  SizedBox(width: screenSize.width/5,),
                  Text(widget.dataMap["vehicleLength"], style: TextStyle(color: Colors.black,fontSize: 13.sp)),
                  Text(widget.dataMap["vehicleModel"], style: TextStyle(color: Colors.black,fontSize: 13.sp)),
                ],
              ),
              SizedBox(height: 8.h,),
              Row(
                children: [
                  Text("货物",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                  SizedBox(width: screenSize.width/5,),
                  Text( widget.dataMap["cargoInfo"][0]['cargoName'],style: TextStyle(color: Colors.black,fontSize: 13.sp)),
                  if(widget.dataMap["cargoInfo"][0]['cargoWeight']!=null)
                    Text( ","+widget.dataMap["cargoInfo"][0]['cargoWeight'].toString()+"吨",style: TextStyle(color: Colors.black,fontSize: 13.sp)),
                  if(widget.dataMap["cargoInfo"][0]['cargoVolume']!=null)
                    Text(  ","+widget.dataMap["cargoInfo"][0]['cargoVolume'].toString()+"方",style: TextStyle(color: Colors.black,fontSize: 13.sp)),

                ],
              ),
              SizedBox(height: 8.h,),
              Row(
                children: [
                  Text("备注",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                  SizedBox(width: screenSize.width/5,),
                  Container(
                    width: 200.w,
                    child:  
                        Text(widget.dataMap['remark'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: Colors.black,fontSize: 13.sp),),

                  ),

                ],
              ),
            ],
          ),
        ),
        Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          padding: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w,bottom: 8.h),
          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("支付信息",style: TextStyle(fontSize: 14.sp,color: Colors.black,fontWeight: FontWeight.w600),),
            Divider(height: 16.h,color: MyColors.backgreyColor,),

            Row(
              children: [
                Text("订金",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                SizedBox(width: screenSize.width/5,),
                (widget.dataMap["deposit"]!=0) ?
                Row(
                  children: [
                    Text((widget.dataMap['deposit']).toString()+"元",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                    SizedBox(width: 8.w,),
                    widget.dataMap['depositType']==0?
                    Text("(退还)",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),):
                    Text("(不退还)",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                  ],)
                    :Text("无订金",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
              ],
            ),
            SizedBox(height: 8.h,),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("担保说明",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                SizedBox(width: screenSize.width/8,),
                Container(
                  width:screenSize.width-150.w ,
                  child: Text(widget.dataMap['depositType']==0?"订金支付至平台监管账户，您确认收货后由平台支付给司机":"订金支付至平台监管账户，您确认收货后由平台支付给您",style: TextStyle(color: Colors.black,fontSize: 13.sp),softWrap: true),
                ),
              ],
            ),

          ],
          ),
        ),
      ],
    );
  }
}

class getDriverList extends StatefulWidget {
  const getDriverList({super.key, required this.dataList, required this.id, required this.shipperId});
  final List dataList;
  final String id;
  final String shipperId;

  @override
  State<getDriverList> createState() => _getDriverListState();
}

class _getDriverListState extends State<getDriverList> {
  List dataList=[];
  int pageNum=1;
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    dataList=widget.dataList;
    getDriverDataAction(widget.id, widget.shipperId);
  }
  void _onRefresh(){
    pageNum=1;
    getDriverDataAction(widget.id, widget.shipperId);
  }
  void _onLoadfresh(){
    if(dataList.length>19*pageNum){
      getDriverDataAction(widget.id, widget.shipperId);
    }
  }
  //获取已联系司机列表
  void getDriverDataAction(String id,String shipperId) async {
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.DriverCantact,
      {"current":pageNum,"size":20,"goodsId":widget.id},
          (responseData) async {
        setState(() {
          if(pageNum==1) {
            dataList = responseData['data']['records'];
          }else if(responseData['data']['records'].isNotEmpty&&pageNum!=1){
            dataList.addAll( responseData['data']['records']);
          }
        });

      },
    );

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return   EasyRefresh(
        header:
        ClassicHeader(
        dragText: '下拉刷新',
        armedText: '准备释放',
        readyText: '加载中...',
        processingText: '加载中...',
        processedText: '刷新成功',
        noMoreText: '暂无更多',
        failedText: '刷新失败',
        messageText: '刷新时间 %T',
    ),
    footer: ClassicFooter(
    dragText: '加载更多',
    armedText: '准备释放',
    readyText: '加载中...',
    processingText: '加载中...',
    processedText: '加载成功',
    noMoreText: '暂无更多',
    failedText: '加载失败',
    messageText: '加载时间 %T',
    ),
    onRefresh: _onRefresh,
    onLoad: dataList.length>19?_onLoadfresh:null,
      child:  dataList.length==0? Container(
        color: Colors.white,
        height:screenSize.height-225.h,
        child:  Center(
            child:   BrnAbnormalStateWidget(
              img: Image.asset(
                'lib/Images/OrderList/找货暂无货源.png',
                scale: 3.0,
              ),
              content: '暂无联系司机',
            )
        ),
      )
     : Container(
        // height: screenSize.height-240.h,
        height: screenSize.height-225.h,
        decoration: BoxDecoration(
            color: MyColors.backgreyColor,
            borderRadius: BorderRadius.all(Radius.circular(10))),

        child: ListView.builder(

            shrinkWrap: false,
            itemCount:  dataList.length,
            itemBuilder: (BuildContext context,
                int index) {
              return  GestureDetector(
                onTap: (){
                  Navigator.push( context, FadeRoute(page:DriverIntroduction(DrvId: dataList[index]['driverId'],)));
                },
                child:    Container(
                  margin: EdgeInsets.only(
                      top: 8.h, left: 15.w, right: 15.w),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(
                          Radius.circular(10))),
                  padding: EdgeInsets.all(10.w),
                  child: Column(

                    children: [

                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Row(
                            children: [
                              ClipOval(
                                child: Image.network(
                                  MyServiceUrl.imgHeader+dataList[index]['avatarPath'],
                                  width: 40.0,
                                  height: 40.0,
                                  fit: BoxFit.cover,
                                ),
                              ),
                              SizedBox(width: 8.w,),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [

                                      Text( dataList[index]['realName'],
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 13.sp),),
                                      Row(
                                        children: List.generate( (divideAndRound(dataList[index]['rating'], 20)), (starIndex) {
                                          return Icon(Icons.star, color: MyColors.themeColor, size: 20.0);
                                        }),
                                      ),
                                    ],
                                  ),
                                  Row(
                                    children: [

                                      if(dataList[index]['vehicleLength']!="")
                                        BrnTagCustom(
                                          tagText: dataList[index]['vehicleLength'].toString()+"米",
                                          backgroundColor: Color.fromRGBO(239, 239, 239, 1),
                                          textColor: Colors.black,
                                          fontSize: 10.sp,
                                        ),
                                      if(dataList[index]['vehicleModel']!="")
                                        BrnTagCustom(
                                          tagText: dataList[index]['vehicleModel'].toString(),
                                          backgroundColor:Color.fromRGBO(239, 239, 239, 1),
                                          textColor: Colors.black,
                                          fontSize: 10.sp,
                                        ),
                                    ],
                                  ),

                                ],
                              ),
                            ],
                          ),


                        ],
                      ),
                      SizedBox(height: 8.h,),
                      Row(
                        children: [
                          // SizedBox(width: 10.w,),
                          Icon(Icons.phone_forwarded,color: MyColors.hintColor,size: 20,),
                          // Text(widget.dataList[index]['phoneNum'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                          SizedBox(width: 10.w,),
                          Text(dataList[index]['createTime'],style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                        ],
                      ),
                      SizedBox(height: 8.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Image.asset("lib/Images/OrderList/IMicon.png", width: 24.w, height: 24.h,),
                          Row(
                            children: [
                              GestureDetector(
                                child:Container(
                                  width: 65.w,
                                  height: 25.h,
                                  decoration: BoxDecoration(
                                      color: MyColors.themeColor,
                                      borderRadius: BorderRadius.all(Radius.circular(30))),
                                  child: Center(
                                    child: Text("指定承运",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.w600),),
                                  ),
                                ) ,
                                onTap: (){
                                  Navigator.push( context, FadeRoute(page:SelectSourceOfGoods(carMap:dataList[index],)));

                                },
                              ),




                              SizedBox(width: 8.w,),
                              GestureDetector(
                                child:Container(
                                  width: 65.w,
                                  height: 25.h,
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                        color:  MyColors.themeColor,
                                        width: 1.0,
                                      ),
                                      color: Colors.white,
                                      borderRadius: BorderRadius.all(Radius.circular(30))),
                                  child: Center(
                                    child: Text("电话联系",style: TextStyle(color: MyColors.themeColor,fontSize: 12.sp,fontWeight: FontWeight.w600),),
                                  ),
                                ) ,
                                onTap: (){
                                  _makePhoneCall(dataList[index]['phoneNum']);
                                },
                              ),

                            ],
                          ),
                        ],
                      ),
                      SizedBox(height: 8.h,),
                    ],
                  ),
                ),
              );

            }
        ),



      ),
    );

  }
}
